package com.wuzao.httpTest;

import java.io.*;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipTest {
    public static void main(String[] args) throws IOException {
        // 假设接收到 GZIP 编码后再 Base64 编码的字符串数据
        String gzipEncodedString = createBase64GzipData("This is the original POST content.你好");

        // 解码 GZIP（Base64 -> GZIP -> 原始内容）
        System.out.println(gzipEncodedString);
        String decodedContent = decodeGzipString(gzipEncodedString);
        System.out.println("Decoded content: " + decodedContent);

        // 修改内容
        String modifiedContent = decodedContent + " Modified by program.";

        // 重新编码为 GZIP，并转为 Base64 字符串
        String reEncodedGzipString = encodeGzipString(modifiedContent);
        System.out.println("Re-encoded GZIP String: " + reEncodedGzipString);
    }

    // 解码 GZIP 编码后的 Base64 字符串
    public static String decodeGzipString(String gzipEncodedString) throws IOException {
        // Base64 解码为 GZIP 字节数据
        byte[] gzipData = Base64.getDecoder().decode(gzipEncodedString);

        // 解码 GZIP 数据
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(gzipData);
             GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
             InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {

            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        }
    }

    // 编码为 GZIP 并转为 Base64 字符串
    public static String encodeGzipString(String content) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
            gzipOutputStream.write(content.getBytes());
        }
        byte[] gzipData = byteArrayOutputStream.toByteArray();

        // Base64 编码 GZIP 数据
        return Base64.getEncoder().encodeToString(gzipData);
    }

    // 模拟生成 GZIP 编码再 Base64 编码的数据
    private static String createBase64GzipData(String content) throws IOException {
        return encodeGzipString(content);
    }
}
